#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <pthread.h>

int tickets = 1000;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;

void *start_routine(void *args)
{
    char *name = (char *)args;
    while (1)
    {
        pthread_mutex_lock(&mutex);
        pthread_cond_wait(&cond, &mutex); // 当前线程去到条件变量下的等待区等待 ，为什么要有锁，后面说
        // 判断暂时省略
        printf("%s -> %d\n", name, tickets);
        tickets--;
        pthread_mutex_unlock(&mutex);
    }
    return NULL;
}

int main()
{
    // 通过条件变量控制线程的执行
    pthread_t t[5];
    for (int i = 0; i < 5; i++)
    {
        char *name = (char *)malloc(64);
        // char name[64];   这种就会导致一直是一个线程执行，无发实现线程同步
        snprintf(name, 64, "thread %d", i + 1);
        pthread_create(t + i, NULL, start_routine, name);
    }

    while (1)
    {
        usleep(1000);
        // 唤醒条件变量下等待区的线程
        pthread_cond_signal(&cond);
        printf("主线程唤醒了一个线程....\n");
    }

    // 等待线程
    for (int i = 0; i < 5; i++)
    {
        pthread_join(t[i], NULL);
    }
}